package com.ydzt.fanka.server.timer;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.ydzt.fanka.server.init.InitData;
import com.ydzt.fanka.server.utils.Convert;
import com.ydzt.fanka.server.utils.DBHelper;
import com.ydzt.fanka.server.zwcl.ZwclEndDayService;

/*
 * 中心自动切换结算日期线程
 * */
public class AutoEndDayServer {

	static String temp_str;
	static String currentSTMT_DAY;
	static Date currentStmtDay;
	static Date time;
	static Logger logger = Logger.getLogger(AutoEndDayServer.class.getName());
	private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;
	public static void endDay(){
		TimerTask task = new TimerTask() {
            @Override
            public void run() {
            	logger.info("日终定时器触发....");
            	currentSTMT_DAY = DBHelper.getStmtDay();
        		time = new Date();
        	    currentStmtDay = Convert.getDateByString(currentSTMT_DAY, "yyyyMMdd");
        	    temp_str = time.toString();
        		//切换结算日期
        		logger.info("当前结算日为:" + currentSTMT_DAY);
        		logger.info("中心自然日为:" + temp_str);
        		long timespan = currentStmtDay.getTime() - time.getTime();
        		long days = timespan / InitData.DAY;
        		if(days != 0){
    				if(timespan > 0){
    					logger.info("中心自然日小于中心结算日 不进行日切");
    					//ZwclEndDayService.AutoEndDayCentre();
    				}
    				else{
    					logger.info("中心自然日大于中心结算日 将进行日切");
    					//logger.info("中心自然日小于中心结算日 将进行日切");
    					ZwclEndDayService.AutoEndDayCentre();
    				}
    			}
    			else{
    				logger.info("中心自然日与中心结算日一致，不做日切操作");
    			}
            }

        };
		Timer timer = new Timer();
		
		Calendar calendar =  Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
	    int month = calendar.get(Calendar.MONTH);
	    int day = calendar.get(Calendar.DAY_OF_MONTH);
	    calendar.set(year, month, day, Integer.parseInt(InitData.HOUR_OF_DAY), Integer.parseInt(InitData.MINUTE), Integer.parseInt(InitData.SECOND));
		Date time = calendar.getTime();
		if(time.before(new Date()))
		{
			time =  addDay(time,1);
		}
		timer.schedule(task, time, PERIOD_DAY);
	}
	
	public static Date addDay(Date date, int num){
		Calendar startDT = Calendar.getInstance();
		startDT.setTime(date);
		startDT.add(Calendar.DAY_OF_MONTH, num);
		return startDT.getTime();
	}
}
